<template>
  <div class="app-container">

    <u-page title="订单管理">

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="订单类型" prop="type">
            <el-select v-model="listQuery.type" placeholder="订单类型" clearable>
              <el-option label="全部" value="" />
              <el-option label="临停" value="0" />
              <el-option label="月租" value="1" />
              <el-option label="商品" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="listQuery.orderNo" placeholder="请输入订单号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="流水号" prop="tradeNo">
            <el-input v-model="listQuery.tradeNo" placeholder="请输入流水号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="卡号" prop="cardNo">
            <el-input v-model="listQuery.cardNo" placeholder="会员卡号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="车牌" prop="plateNo">
            <el-input v-model="listQuery.plateNo" placeholder="车牌" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="交易状态" prop="status">
            <el-select v-model="listQuery.status" placeholder="请选择交易状态" class="status" clearable>
              <el-option label="全部" value="" />
              <el-option label="已关闭" :value="-1" />
              <el-option label="待付款" :value="0" />
              <el-option label="已完成" :value="3" />
              <el-option label="已退款" :value="4" />
              <el-option label="退款失败" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="交易时间">
            <u-date-time-picker v-model="searchDate" value-format="yyyy-MM-dd HH:mm:ss" @change="changeSearchDate" />
          </el-form-item>
          <el-form-item label="业务处理" class="businessStatus">
            <el-select v-model="listQuery.businessStatus" placeholder="业务处理" clearable>
              <el-option label="全部" value="" />
              <el-option label="成功" value="1" />
              <el-option label="失败" value="2" />
              <el-option label="待处理" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="上报状态" class="ack">
            <el-select v-model="listQuery.ack" placeholder="上报状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="成功" value="1" />
              <el-option label="失败" value="2" />
              <el-option label="待上报" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="退款状态">
            <el-select v-model="listQuery.refundApplyState" placeholder="退款状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="未申请" value="0" />
              <el-option label="申请中" value="1" />
              <el-option label="审核失败" value="2" />
              <el-option label="审核成功" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="会员权益" prop="checked">
            <el-checkbox v-model="listQuery.checked"></el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <u-table
        index="index"
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right" width="200">
            <template slot-scope="{ row }">
              <el-button v-if="row.ack === 2" type="text" @click="hdlRetryById(row)">重传</el-button>
              <el-button type="text" @click="hdlEdit(row)">交易记录</el-button>
              <el-button v-if="row.status === 3 && row.refundApplyState !== 1 " type="text" @click="hdlOpenRefundApply(row)">退款申请</el-button>
              <el-button v-if="row.status === 3 && row.refundApplyState === 1 " type="text" @click="hdlRefund(row)">退款审核</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>

    <!-- 订单信息 -->
    <u-dialog title="订单详情" :show.sync="dialogFormVisible" :footer="false" @confirm="hdlUpdate()">
      <el-form ref="dialogForm" :rules="rules" :model="dataForm" label-position="top" label-width="80px">

        <el-descriptions :column="2" border style="margin-bottom: 10px">
          <el-descriptions-item label="订单号">{{ dataForm.orderNo }}</el-descriptions-item>

          <el-descriptions-item label="交易时间">{{ dataForm.createTime }}</el-descriptions-item>

          <el-descriptions-item label="订单类型">
            <el-tag v-if="dataForm.type === 0" type="success">临停</el-tag>
            <el-tag v-if="dataForm.type === 1" type="success">月租</el-tag>
            <el-tag v-if="dataForm.type === 2" type="success">商品</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="交易状态">
            <el-tag v-if="dataForm.status === -1" type="info">已关闭</el-tag>
            <el-tag v-if="dataForm.status === 0" type="danger">待付款</el-tag>
            <el-tag v-if="dataForm.status === 3" type="success">已完成</el-tag>
            <el-tag v-if="dataForm.status === 4" type="success">已退款</el-tag>
            <el-tag v-if="dataForm.status === 5" type="danger">退款失败</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="支付方式">
            <el-tag v-if="dataForm.payType === 21" type="success">微信支付</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="支付时间">
            <div v-if="dataForm.payTime">
              <el-tag type="success">{{ dataForm.payTime }}</el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="流水号">
            <div v-if="dataForm.tradeNo">
              <el-tag>{{ dataForm.tradeNo }}</el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="总金额/元">
            <el-tag type="success">{{ $u.amount.F2Y(dataForm.totalFee) }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="优惠金额/元">
            <el-tag type="warning">{{ $u.amount.F2Y(dataForm.discFee) }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="实付金额/元">
            <el-tag type="success">{{ $u.amount.F2Y(dataForm.paidFee) }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="会员卡号">
            {{ dataForm.cardNo }}
          </el-descriptions-item>

          <el-descriptions-item label="OPENID">
            {{ dataForm.openid }}
          </el-descriptions-item>

          <template v-if="dataForm.type === 0">
            <el-descriptions-item label="车牌号">{{ dataForm.plateNo }}</el-descriptions-item>
            <el-descriptions-item label="科拓订单">{{ dataForm.parkingOrderNo }}</el-descriptions-item>
            <el-descriptions-item label="入场时间">{{ dataForm.entryTime }}</el-descriptions-item>
            <el-descriptions-item label="停车通道">{{ dataForm.parkChannel }}</el-descriptions-item>

            <el-descriptions-item label="放行状态" :span="2">
              <el-tag v-if="dataForm.parkingState === 0" type="warning">未放行</el-tag>
              <el-tag v-if="dataForm.parkingState === 1" type="success">放行成功</el-tag>
              <el-tag v-if="dataForm.parkingState === 2" type="danger">放行失败</el-tag>
              {{ dataForm.parkingFailMsg }}
            </el-descriptions-item>

            <!-- 合并抵扣信息 -->
            <el-descriptions-item label="优惠抵扣" :span="2">
              <div v-if="dataForm.benefitStatus !== 0">
                <span>权益抵扣：</span>
                <span>
                  {{ getStatusText(dataForm.benefitStatus, ['未抵扣', '抵扣成功', '抵扣失败']) }}
                </span>
                <span v-if="dataForm.benefitStatus === 1">（{{ dataForm.benefit }}小时，抵扣金额：{{ $u.amount.F2Y(dataForm.benefitFee) }} 元）</span>
              </div>
              <div v-if="dataForm.creditStatus !== 0">
                <span>积分抵扣：</span>
                <span>
                  {{ getStatusText(dataForm.creditStatus, ['未抵扣', '抵扣成功', '抵扣失败']) }}
                </span>
                <span v-if="dataForm.creditStatus === 1">（{{ dataForm.credit }}积分，抵扣金额：{{ $u.amount.F2Y(dataForm.creditFee) }} 元）</span>
              </div>
              <div v-if="dataForm.couponStatus !== 0">
                <span>优惠券抵扣：</span>
                <span>
                  {{ getStatusText(dataForm.couponStatus, ['未抵扣', '抵扣成功', '抵扣失败']) }}
                </span>
                <span >（{{ formatDiscInfo(dataForm.couponBody).length }}张优惠券，抵扣金额：{{ $u.amount.F2Y(dataForm.couponFee) }} 元）</span>
                <div style="margin-top: 10px;">
                  <div  v-for="(item, index) in formatDiscInfo(dataForm.couponBody)" :key="index" style="margin-bottom: 8px; padding: 8px; background-color: #f5f5f5; border-radius: 4px;">
                    {{ item }}
                  </div>
                </div>
              </div>
            </el-descriptions-item>
          </template>
          <template v-if="dataForm.type === 2">
            <el-descriptions-item label="劵号" :span="2">{{ dataForm.extend }}</el-descriptions-item>
          </template>
          <template v-if="dataForm.type === 1 || dataForm.type === 3">
            <el-descriptions-item v-if="dataForm.type === 1 || dataForm.type === 3" label="车牌号" :span="2">{{ dataForm.plateNo }}</el-descriptions-item>
          </template>

          <el-descriptions-item label="业务处理" :span="2">
            <div v-if="dataForm.status >= 3">
              <el-tag v-if="dataForm.businessStatus === '0'" type="warning">待处理</el-tag>
              <el-tag v-if="dataForm.businessStatus === '1'" type="success">成功</el-tag>
              <el-tag v-if="dataForm.businessStatus === '2'" type="danger">失败</el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="备注" :span="2">{{ dataForm.note }}</el-descriptions-item>

        </el-descriptions>

        <el-descriptions v-if="dataForm.status > 3" :column="2" title="订单退款" border style="margin-top: 20px">
          <el-descriptions-item label="退款订单号">{{ dataForm.refundNo }}</el-descriptions-item>

          <el-descriptions-item label="退款时间">{{ dataForm.refundTime }}</el-descriptions-item>

          <el-descriptions-item label="退款流水号">
            <div v-if="dataForm.refundChannelNo">
              <el-tag>{{ dataForm.refundChannelNo }}</el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="退款金额/元">
            <el-tag type="success">{{ $u.amount.F2Y(dataForm.refundFee) }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="退款状态">
            <div v-if="dataForm.status >= 3">
              <el-tag v-if="dataForm.refundApplyState === 0">未申请</el-tag>
              <el-tag v-if="dataForm.refundApplyState === 1" type="warning">申请中</el-tag>
              <el-tag v-if="dataForm.refundApplyState === 2" type="danger">审核失败</el-tag>
              <el-tag v-if="dataForm.refundApplyState === 3" type="success">审核成功</el-tag>
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="退款申请人">{{ dataForm.refundApplyUser }}</el-descriptions-item>

          <el-descriptions-item label="退款审核人">{{ dataForm.refundUser }}</el-descriptions-item>

          <el-descriptions-item v-if="dataForm.status === 5" label="退款失败原因">{{ dataForm.refundMsg }}</el-descriptions-item>

        </el-descriptions>

      </el-form>
    </u-dialog>

    <u-dialog title="上报数据" :show.sync="jsonDialogVisible" :footer="false" width="45%" class="code">
      <el-input v-model="detailJson" autosize type="textarea" disabled placeholder="{}" />
    </u-dialog>

    <!-- 退款申请 -->
    <u-dialog title="订单退款申请" :show.sync="dialogRefundFormVisible" @confirm="hdlRefundApply()">
      <el-form ref="dataRefundForm" :rules="refundRules" :model="dataRefundForm" label-width="80px">

        <el-descriptions :column="2" border style="margin-bottom: 10px">
          <el-descriptions-item label="订单号">{{ dataRefundForm.orderNo }}</el-descriptions-item>

          <el-descriptions-item label="订单类型">
            <el-tag v-if="dataRefundForm.type === 0" type="success">临停</el-tag>
            <el-tag v-if="dataRefundForm.type === 1" type="success">月租</el-tag>
            <el-tag v-if="dataRefundForm.type === 2" type="success">商品</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="交易时间">{{ dataRefundForm.createTime }}</el-descriptions-item>

          <el-descriptions-item label="交易状态">
            <el-tag v-if="dataRefundForm.status === -1" type="info">已关闭</el-tag>
            <el-tag v-if="dataRefundForm.status === 3" type="success">已完成</el-tag>
            <el-tag v-if="dataRefundForm.status === 0" type="danger">待付款</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="支付时间">
            <div v-if="dataRefundForm.payTime">
              {{ dataRefundForm.payTime }}
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="流水号">
            <div v-if="dataRefundForm.tradeNo">
              {{ dataRefundForm.tradeNo }}
            </div>
          </el-descriptions-item>

          <el-descriptions-item label="总金额/元">
            {{ $u.amount.F2Y(dataRefundForm.totalFee) }}
          </el-descriptions-item>

          <el-descriptions-item label="优惠金额/元">
            {{ $u.amount.F2Y(dataRefundForm.discFee) }}
          </el-descriptions-item>

          <el-descriptions-item label="实付金额/元" :span="2">
            {{ $u.amount.F2Y(dataRefundForm.paidFee) }}
          </el-descriptions-item>

          <el-descriptions-item label="退款金额" :span="2">
            <el-form-item prop="refundType" label-width="auto">
              <el-radio-group v-model="dataRefundForm.refundType">
                <el-radio :label="0">
                  全额退款
                  <el-tooltip class="item" effect="dark" content="包含优惠券" placement="top">
                    <i class="el-icon-question" />
                  </el-tooltip>
                </el-radio>
                <el-radio :label="1">
                  部分退款
                  <el-tooltip class="item" effect="dark" content="不包含优惠券" placement="top">
                    <i class="el-icon-question" />
                  </el-tooltip>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>

          <template v-if="dataRefundForm.refundType === 1 ">
            <el-descriptions-item label="退款金额" :span="2">
              <el-form-item prop="refundAmount" label-width="auto">
                <el-input v-model="dataRefundForm.refundAmount" placeholder="请输入退款金额" clearable @input="onKeyInput" />
              </el-form-item>
            </el-descriptions-item>
          </template>

          <el-descriptions-item label="备注" :span="2">
            <el-form-item prop="remark" label-width="auto">
              <el-input v-model="dataRefundForm.remark" type="textarea" placeholder="请输入备注以方便追溯历史原因(必填)" clearable maxlength="200" show-word-limit />
            </el-form-item>
          </el-descriptions-item>

        </el-descriptions>

      </el-form>
    </u-dialog>
  </div>
</template>
<script>

export default {
  components: { },
  data() {
    return {
      api: this.$u.api.PluginsParkingOrder,
      list: [],
      listLoading: false,
      listOptions: {
        mutiSelect: true,
        stripe: true
      },
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1,
        beginTime: '',
        endTime: '',
        orderNo: '',
        tradeNo: '',
        ack: '',
        status: '',
        businessStatus: '',
        refundApplyState: ''
      },
      inputDateRange: [],
      // 表格
      columns: [
        {
          prop: 'createTime',
          label: '交易时间',
          width: '150',
        },
        {
          prop: 'orderNo',
          label: '订单号',
          width: '166'
        },
        {
          prop: 'type',
          label: '订单类型',
          width: '120',
          render: (h, params) => {
            const { type } = params.row
            let title = ''
            if (type === 0) {
              title = '临停'
            }
            if (type === 1) {
              title = '月租'
            }
            if (type === 2) {
              title = '商品'
            }
            return h('el-tag', title)
          }
        },
        {
          prop: 'cardNo',
          label: '卡号',
          width: '166'
        },
        {
          prop: 'openid',
          label: 'OPENID',
          width: '230'
        },
        {
          prop: 'tradeNo',
          label: '流水号',
          width: '240'
        },
        {
          prop: 'payTime',
          label: '支付时间',
          width: '150'
        },
        {
          prop: 'totalFee',
          label: '总金额/元',
          width: '100',
          render: (h, params) => {
            const { totalFee } = params.row
            return h('el-tag', { props: { type: 'success' }}, this.$u.amount.F2Y(totalFee))
          }
        },
        {
          prop: 'discFee',
          label: '优惠金额/元',
          width: '100',
          render: (h, params) => {
            const { discFee } = params.row
            return h('el-tag', { props: { type: 'warning' }}, this.$u.amount.F2Y(discFee))
          }
        },
        {
          prop: 'paidFee',
          label: '实付金额/元',
          width: '100',
          render: (h, params) => {
            const { paidFee } = params.row
            return h('el-tag', { props: { type: 'success' }}, this.$u.amount.F2Y(paidFee))
          }
        },
        {
          prop: 'payType',
          label: '支付方式',
          width: '100',
          render: (h, params) => {
            return h('div', '微信支付')
          }
        },
        {
          prop: 'status',
          label: '交易状态',
          width: '100',
          render: (h, params) => {
            const { status } = params.row
            let title = '待付款'
            let type = 'warning'
            if (status === -1) {
              title = '已关闭'
              type = 'info'
            } else if (status === 3) {
              title = '已完成'
              type = 'success'
            } else if (status === 4) {
              title = '已退款'
              type = 'success'
            } else if (status === 5) {
              title = '退款失败'
              type = 'danger'
            }
            return h('el-tag', { props: { type }}, title)
          }
        },
        {
          prop: 'plateNo',
          label: '车牌',
          width: '150',
          render: (h, params) => {
            const { plateNo } = params.row
            if (plateNo) {
              return h('el-tag', plateNo)
            }
          }
        },
        {
          prop: 'businessStatus',
          label: '业务处理',
          render: (h, params) => {
            const { status, businessStatus } = params.row
            let title = '待处理'
            let type = 'warning'
            if (businessStatus === '1') {
              title = '成功'
              type = 'success'
            } else if (businessStatus === '2') {
              title = '失败'
              type = 'danger'
            }
            if (status >= 3) {
              return h('el-tag', { props: { type }}, title)
            }
          }
        },
        {
          prop: 'ack',
          label: '上报状态',
          render: (h, params) => {
            const { status, ack } = params.row
            let title = '待上报'
            let type = 'warning'
            if (ack === 1) {
              title = '成功'
              type = 'success'
            } else if (ack === 2) {
              title = '失败'
              type = 'danger'
            }
            if (status >= 3) {
              return h('el-tag', { props: { type }}, title)
            }
          }
        },
        {
          prop: 'ack',
          label: '上报内容',
          render: (h, params) => {
            return h('el-button', { props: { type: 'text' }, on: {
              click: () => this.orderDetailToJson(params.row)
            }}, '上报内容')
          }
        },
        {
          prop: 'note',
          label: '备注'
        }
      ],

      dialogFormVisible: false,
      dialogStatus: '',

      dataForm: {},
      rules: {
        note: [
          { required: true, message: '请输入备注信息', trigger: ['blur'] }
        ]
      },
      jsonDialogVisible: false,
      detailJson: {},

      // 退款
      dialogRefundFormVisible: false,
      dataRefundForm: {
        refundType: 0
      },
      refundRules: {
        refundType: [
          { required: true, message: '请选择退款类型', trigger: ['blur'] }
        ],
        note: [
          { required: true, message: '请输入备注信息', trigger: ['blur'] }
        ]
      }
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    getTagType(status, types) {
      return types[status] || '';
    },
    getStatusText(status, texts) {
      return texts[status] || '';
    },
    // 核销响应信息格式化
    formatCouponResult(item) {
      const json = JSON.parse(item)
      const data = {
        '交易号': json.tranNo,
        '优惠券消费详情': {
          '优惠券编号': '',
          '财务列表': {}
        }
      }
      json.couponConsumeDetail.forEach(coupon => {
        // '优惠券编号': coupon.couponNo,
        data.优惠券消费详情.优惠券编号 = coupon.couponNo
        coupon.financeList.forEach(item => {
          data.优惠券消费详情.财务列表 = {
            '账号': item.accountNo,
            '优惠券标题': item.accountTitle,
            '优先级': item.accountPriority,
            '金额': item.accountValue
          }
        })
      })
      console.log(data)
      return JSON.stringify(data)
    },
    // 数据格式化
    formatExtendInfo(item) {
      const json = JSON.parse(item)
      let formattedResult = {}
      if (typeof json === 'object') {
        formattedResult = {
          '订单号': json.orderNo,
          '车牌号': json.plateNo,
          '入场时间': json.entryTime,
          '支付时间': json.payTime,
          '停车时长(分)': json.elapsedTime,
          '停车时长': json.elapsed,
          '优惠券列表': json.couponList,
          '总费用': json.totalFee,
          '优惠费用': json.discFee,
          '实付费用': json.paidFee
        }
      } else {
        formattedResult = {
          '券号': json
        }
      }

      const data = []
      // 输出转换后的结果
      for (const [key, value] of Object.entries(formattedResult)) {
        const formattedData = `${key}: ${value}`
        data.push(formattedData)
      }
      return data
    },
    // 导出数据
    handleDownload() {
      // 复制值
      const list = this.$u.deepClone(this.list)
      // 业务数据处理
      list.forEach(item => {
        this.$set(item, 'status', item.status === 0 ? '待付款' : item.status === -1 ? '已关闭' : item.status === 3 ? '已完成' : item.status === 4 ? '已退款' : item.status === 5 ? '退款失败' : '')
        this.$set(item, 'type', item.type === 0 ? '临停' : item.type === 1 ? '月租' : item.type === 2 ? '商品' : '')
        this.$set(item, 'totalFee', item.totalFee ? this.$u.amount.F2Y(item.totalFee) : '')
        this.$set(item, 'discFee', item.discFee ? this.$u.amount.F2Y(item.discFee) : '')
        this.$set(item, 'paidFee', item.paidFee ? this.$u.amount.F2Y(item.paidFee) : '')
        this.$set(item, 'payType', item.payType === 21 ? '微信支付' : '')
        this.$set(item, 'fullRefund', item.fullRefund === 1 ? '是' : '否')
        this.$set(item, 'refundFee', item.refundFee ? this.$u.amount.F2Y(item.refundFee) : '')
        this.$set(item, 'discInfo', item.discInfo ? this.formatDiscInfo(item.discInfo) : '')
        this.$set(item, 'businessStatus', item.businessStatus === 1 ? '成功' : item.businessStatus === 2 ? '失败' : '')
        this.$set(item, 'ack', item.ack === 0 ? '待处理' : item.ack === 1 ? '成功' : item.ack === 2 ? '失败' : '')
        this.$set(item, 'parkingState', item.parkingState === 0 ? '未放行' : item.parkingState === 1 ? '成功' : item.parkingState === 2 ? '失败' : '')
        this.$set(item, 'memberScoreState', item.marketCouponState === 0 ? '未抵扣' : item.marketCouponState === 1 ? '成功' : item.marketCouponState === 2 ? '失败' : '')
        this.$set(item, 'memberScore', `使用抵扣积分：${item.memberScore}，抵扣金额：${this.$u.amount.F2Y(item.memberScoreFee)}`)
        this.$set(item, 'couponStatus', item.couponStatus === 0 ? '未抵扣' : item.couponStatus === 1 ? '成功' : item.couponStatus === 2 ? '失败' : '')
        // this.$set(item, 'extend', item.extend ? this.formatExtendInfo(item.extend) : '')
        this.$set(item, 'couponConsumeResult', item.couponConsumeResult ? this.formatCouponResult(item.couponConsumeResult) : '')
        this.$set(item, 'refundApplyState', item.refundApplyState === 0 ? '未申请' : item.refundApplyState === 1 ? '申请中' : item.refundApplyState === 2 ? '审核失败' : item.refundApplyState === 3 ? '审核通过' : '')
      })
      console.log(list)
      // 表头&表数据
      const tHeader = ['交易时间', '支付时间', '订单类型', '订单号', '交易流水号', 'openid', '会员卡号', '支付类型', '订单总金额', '优惠金额', '实付金额', '订单状态', '业务状态', '上报数据', '上报失败原因', '科拓订单号', '车牌号', '等级', '停车场通道', '车辆入场时间', '放行状态', '放行失败原因', '积分抵扣状态', '积分抵扣信息', '优惠券抵扣状态', '优惠券抵扣信息', '优惠券核销响应信息', '退款订单号', '退款流水号', '是否全额退款', '退款金额', '退款时间', '退款失败原因', '退款状态', '退款申请人', '退款审核人', '订单备注']
      const filterVal = ['createTime', 'payTime', 'type', 'orderNo', 'tradeNo', 'openid', 'cardNo', 'payType', 'totalFee', 'discFee', 'paidFee', 'status', 'businessStatus', 'ack', 'ackMsg', 'parkingOrderNo', 'plateNo', 'vipLevel', 'parkChannel', 'entryTime', 'parkingState', 'parkingFailMsg', 'memberScoreState', 'memberScore', 'couponStatus', 'discInfo', 'couponConsumeResult', 'refundNo', 'refundChannelNo', 'fullRefund', 'refundFee', 'refundTime', 'refundMsg', 'refundApplyState', 'refundApplyUser', 'refundUser', 'note']
      const data = list.map(v => filterVal.map(j => { return v[j] }))
      this.$u.exports.excel('停车订单记录', tHeader, data)
    },
    // 查看传输内容
    orderDetailToJson(row) {
      const { body } = row
      const content = body ? JSON.parse(body) : {}
      console.log(content)
      this.detailJson = JSON.stringify(content, null, '\t')
      this.jsonDialogVisible = true
    },
    // 重试
    hdlRetryById(row) {
      const { id } = row
      const self = this
      self.$confirm('确定进行重传?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        self.api.fetchByRetryId(id).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg('操作成功')
        })
      }).catch(() => {
      })
    },
    // 退款申请
    hdlOpenRefundApply(row) {
      const self = this
      // 初始化数据源
      self.dataRefundForm = Object.assign({ refundType: 0, refundAmount: 0 }, row)
      // 打开弹框状态
      self.dialogRefundFormVisible = true
      // 清除表单验证状态
      self.$nextTick(() => {
        self.$refs['dataRefundForm'].clearValidate()
      })
    },
    // 退款申请操作
    hdlRefundApply() {
      const self = this
      const { id, orderNo, refundType, remark, refundAmount } = self.dataRefundForm
      const d = { id, refundType, remark, refundAmount, refundFee: 0 }
      d.refundFee = this.$u.amount.Y2F(refundAmount)

      // 效验数据格式
      self.$refs['dataRefundForm'].validate((valid) => {
        if (valid) {
          // 模态对话框组件
          self.$confirm('此操作将订单:' + orderNo + '退款申请后将不能恢复，是否继续？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
            // 处理确认事件
            self.api.refundApply(d).then(() => {
              // 刷新数据列表
              self.hdlList()
              // 关闭弹窗状态
              self.dialogRefundFormVisible = false
              // 通知信息
              self.$u.msg('申请成功')
            })
          }).catch(() => {
          })
        }
      })
    },
    // 退款审核操作
    hdlRefund(row) {
      const self = this
      const { id, orderNo, fullRefund, refundFee } = row

      let message = '此操作将订单：' + orderNo
      // 是否全额退款
      if (fullRefund) {
        message = message + '全额退款？'
      } else {
        message = message + '部分退款？退款金额：' + this.$u.amount.F2Y(refundFee) + '元'
      }

      // 模态对话框组件
      self.$confirm(message, '提示', { distinguishCancelAndClose: true, confirmButtonText: '同意', cancelButtonText: '拒绝', type: 'warning' }).then(() => {
        // 处理确认事件
        self.api.refund({ 'id': id, 'reject': false }).then(() => {
          // 刷新数据列表
          self.hdlList()
          // 通知信息
          self.$u.msg('操作成功')
        })
      }).catch(action => {
        if (action === 'cancel') {
          // 处理确认事件
          self.api.refund({ 'id': id, 'reject': true }).then(() => {
            // 刷新数据列表
            self.hdlList()
            // 通知信息
            self.$u.msg('操作成功')
          })
        }
      })
    },
    onKeyInput(value) {
      let payAmount = value
      // 如果输入非数字，则替换为''
      payAmount = payAmount.replace(/[^\d\.]/g, '')
      // 必须保证第一个为数字而不是.
      payAmount = payAmount.replace(/^\./g, '')
      // 保证只有出现一个.而没有多个.
      payAmount = payAmount.replace(/\.{2,}/g, '.')
      // 保证.只出现一次，而不能出现两次以上
      payAmount = payAmount.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      // 只能输入两位小数
      payAmount = payAmount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      if (payAmount.indexOf('.') < 0 && payAmount !== '') {
        payAmount = parseFloat(payAmount)
      }
      setTimeout(() => {
        this.dataRefundForm.refundAmount = payAmount
      }, 0)
    },
    // 格式化信息
    formatDiscInfo(json) {
      if (!json) return []; // 如果 json 为空，直接返回空数组

      try {
        const jsonArray = JSON.parse(json); // 解析 JSON 字符串

        // 格式化每条优惠券信息
        return jsonArray.map(coupon => {
          return `${coupon.couponName}元停车满减券，券号：${coupon.couponNo}，抵扣金额：${coupon.deductionAmount}`;
        });
      } catch (error) {
        console.error('解析优惠券信息失败:', error); // 打印错误信息
        return []; // 返回空数组，避免程序崩溃
      }
    }
  }
}
</script>
<style lang="scss" scoped>

.app-container{
  ::v-deep {
    .filter {
      border: 0;
    }

    .code .el-textarea.is-disabled .el-textarea__inner {
      background-color: #060606 !important;
      color: #c6c6c6 !important;
    }

    .ack .el-input{
      width: 120px;
    }
  }
}
.orderinfo{
  width: 100%;
  display: flex;
  border: 1px solid #dfe6ec;
}

.goodinfolist{
  width: 70%;
  border-right:2px solid #dfe6ec ;
}
.goodinfotitle{
  padding: 5px;
  text-align: center;
  display: flex;
  width: 100%;
  background-color: #d5dbe7;
}
.goodinfotitle span {
  width:25%;
}
.goodinfo{
  padding: 5px;
  text-align: center;
  display: flex;
  height: 30px;
}
.goodinfo div{
  padding: 2px;
  width:20%;
  border-bottom: 1px solid #dfe6ec;
}
.payinfolist{
  width: 30%;
}
.payinfotitle{
  padding: 5px;
  text-align: center;
  display: flex;
  width: 100%;
  background-color: #d5dbe7;
}
.payinfotitle span {
  width:50%;
}
.payinfo{
  padding: 5px;
  text-align: center;
  display: flex;
  height: 30px;
}
.payinfo div{
  padding: 2px;
  width:50%;
  border-bottom: 1px solid #dfe6ec;
}

</style>
